<template>
	<view class="verification-page">
		<!-- 头部 -->
		<u-navbar 
			title="实名认证"
			:border="false"
			bgColor="#FFFFFF"
			titleColor="#333333"
			:titleStyle="{ fontSize: '36rpx', fontWeight: '500' }"
			leftIcon="arrow-left"
			@leftClick="goBack"
			placeholder
		></u-navbar>

		<!-- 介绍文字 -->
		<view class="intro-text">
			<u-text 
				text="为能够报名高薪企业,入职后享受预支、查看工资条等服务,请填写与您身份证一致的信息。"
				size="14"
				color="#666666"
			></u-text>
		</view>

		<!-- 身份证上传区域 -->
		<IdentityUpload 
			v-model:front="idCardFront"
			v-model:back="idCardBack"
			@ocr-success="handleOcrSuccess"
			@ocr-error="handleOcrError"
		/>

		<!-- 表单字段 -->
		<view class="form-section">
			<u-form 
				:model="formData" 
				:rules="formRules"
				:ref="formRef"
				:label-position="'top'"
				:label-width="'auto'"
				:label-color="'#333333'"
			>
				<u-form-item 
					label="真实姓名" 
					prop="realName"
					:required="true"
				>
					<u-input 
						v-model="formData.realName"
						placeholder="请输入姓名"
						:border="false"
						:custom-style="inputStyle"
						@blur="validateRealName"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="身份证号" 
					prop="idNumber"
					:required="true"
				>
					<u-input 
						v-model="formData.idNumber"
						placeholder="请输入身份证号"
						:border="false"
						:custom-style="inputStyle"
						@blur="validateIdNumber"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="手机号" 
					prop="phone"
					:required="true"
				>
					<u-input 
						v-model="formData.phone"
						placeholder="请输入手机号"
						:border="false"
						:custom-style="inputStyle"
						@blur="validatePhone"
					>
						<template #suffix>
							<u-button 
								type="info" 
								size="mini" 
								:custom-style="codeBtnStyle"
								:disabled="!formData.phone.trim() || !/^1[3-9]\d{9}$/.test(formData.phone.trim()) || isCountingDown"
								@click="getVerificationCode"
							>
								{{ isCountingDown ? `${countdown}s` : '获取验证码' }}
							</u-button>
						</template>
					</u-input>
				</u-form-item>
				
				<u-form-item 
					label="验证码" 
					prop="verificationCode"
					:required="true"
				>
					<u-input 
						v-model="formData.verificationCode"
						placeholder="请输入验证码"
						:border="false"
						:custom-style="inputStyle"
						@blur="validateVerificationCode"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="生日" 
					prop="birthday"
					:required="true"
				>
					<u-input 
						v-model="formData.birthday"
						placeholder="请选择生日"
						:border="false"
						:custom-style="inputStyle"
						readonly
						@click="showBirthdayPicker"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="性别" 
					prop="gender"
					:required="true"
				>
					<u-radio-group v-model="formData.gender" placement="row" @change="onGenderChange">
						<u-radio label="男" name="男"></u-radio>
						<u-radio label="女" name="女"></u-radio>
					</u-radio-group>
				</u-form-item>
				
				<u-form-item 
					label="年龄" 
					prop="age"
					:required="true"
				>
					<u-input 
						v-model="formData.age"
						placeholder="请输入年龄"
						:border="false"
						:custom-style="inputStyle"
						type="number"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="民族" 
					prop="nationalityID"
					:required="true"
				>
					<u-picker
						:show="showNationalityPicker"
						:columns="[nationalityList.map(item => item.fullName)]"
						:defaultIndex="[getNationalityDefaultIndex()]"
						@confirm="onNationalitySelect"
						@cancel="showNationalityPicker = false"
						:customStyle="{ 
							confirmColor: '#FF6B35',
							cancelColor: '#666666'
						}"
					/>
					<view class="select-input" @click="showNationalityPicker = true">
						<text class="select-text" :class="{ placeholder: !formData.nationalityName }">
							{{ formData.nationalityName || '请选择民族' }}
						</text>
						<text class="arrow-icon">▼</text>
					</view>
				</u-form-item>
				
				<u-form-item 
					label="住址" 
					prop="address"
					:required="true"
				>
					<u-input 
						v-model="formData.address"
						placeholder="请输入住址"
						:border="false"
						:custom-style="inputStyle"
					></u-input>
				</u-form-item>
				
		<u-form-item 
			label="籍贯" 
			prop="nativePlace"
			:required="true"
		>
			<u-picker
				:show="showNativePlacePicker"
				:columns="[provinceList.map(item => item.fullName || item.name)]"
				:defaultIndex="[getNativePlaceDefaultIndex()]"
				@confirm="onNativePlaceSelect"
				@cancel="showNativePlacePicker = false"
				:customStyle="{ 
					confirmColor: '#FF6B35',
					cancelColor: '#666666'
				}"
			/>
			<view class="select-input" @click="showNativePlacePicker = true">
				<text class="select-text" :class="{ placeholder: !formData.nativePlace }">
					{{ formData.nativePlace || '请选择籍贯' }}
				</text>
				<text class="arrow-icon">▼</text>
			</view>
		</u-form-item>
				
				<u-form-item 
					label="身份证有效期开始" 
					prop="idCardValidStart"
					:required="true"
				>
					<u-input 
						v-model="formData.idCardValidStart"
						placeholder="请选择有效期开始日期"
						:border="false"
						:custom-style="inputStyle"
						readonly
						@click="showIdCardStartDatePicker"
					></u-input>
				</u-form-item>
				
				<u-form-item 
					label="身份证有效期结束" 
					prop="idCardValidEnd"
					:required="true"
				>
					<u-input 
						v-model="formData.idCardValidEnd"
						placeholder="请选择有效期结束日期"
						:border="false"
						:custom-style="inputStyle"
						readonly
						@click="showIdCardEndDatePicker"
					></u-input>
				</u-form-item>
			</u-form>
		</view>

		<!-- 底部固定区域 -->
		<view class="bottom-section">
			<!-- 协议勾选 -->
			<view class="agreement-section">
				<u-checkbox-group v-model="agreed">
					<u-checkbox 
						:name="true"
						shape="circle"
						:custom-style="checkboxStyle"
						active-color="var(--u-primary)"
					></u-checkbox>
				</u-checkbox-group>
				<text class="agreement-text">
					我已阅读并同意
					<text class="agreement-link" @click="viewAgreement">《个人实名认证服务协议》</text>
				</text>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-section">
				<u-button 
					type="primary"
					:disabled="!isFormValid"
					@click="submitVerification"
					:custom-style="submitBtnStyle"
				>
					立即认证
				</u-button>
			</view>
		</view>
		
		<!-- 民族选择器 -->
		<u-picker 
			v-model="showNationalityPicker"
			:columns="[nationalityList.map(item => ({ label: item.label || item.name, value: item.value || item.id }))]"
			@confirm="onNationalitySelect"
			@cancel="showNationalityPicker = false"
		></u-picker>
		
		
		<!-- 生日日期选择器 -->
		<u-datetime-picker 
			v-model="showBirthdayDatePicker"
			mode="date"
			@confirm="onBirthdaySelect"
			@cancel="showBirthdayDatePicker = false"
		></u-datetime-picker>
		
		<!-- 身份证有效期开始日期选择器 -->
		<u-datetime-picker 
			v-model="showIdCardStartPicker"
			mode="date"
			@confirm="onIdCardStartSelect"
			@cancel="showIdCardStartPicker = false"
		></u-datetime-picker>
		
		<!-- 身份证有效期结束日期选择器 -->
		<u-datetime-picker 
			v-model="showIdCardEndPicker"
			mode="date"
			@confirm="onIdCardEndSelect"
			@cancel="showIdCardEndPicker = false"
		></u-datetime-picker>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { userApi, verifyApi,systemApi } from '@/api/api-helper.js'
import IdentityUpload from '@/components/IdentityUpload.vue'
import { userStore } from '@/stores/userStore'

// 身份证图片
const idCardFront = ref('')
const idCardBack = ref('')

// OCR验证数据
const ocrData = ref({
	front: null,
	back: null
})

// 用户openId（从缓存获取）
const openId = ref(userStore.getOpenId() || '')

// 表单数据
const formData = ref({
	realName: '',
	idNumber: '',
	phone: '',
	verificationCode: '',
	birthday: '', // 生日
	gender: '', // 性别（显示值）
	genderID: '', // 性别ID（提交值）
	age: '', // 年龄
	nationalityID: '', // 民族ID
	nationalityName: '', // 民族名称（用于显示）
	address: '', // 住址
	nativePlace: '', // 籍贯（显示值）
	nativePlaceID: '', // 籍贯ID（提交值）
	idCardValidStart: '', // 身份证有效期开始
	idCardValidEnd: '' // 身份证有效期结束
})

// 监听表单数据变化
watch(formData, (newVal) => {
	console.log('表单数据变化:', newVal)
}, { deep: true })

// 协议勾选
const agreed = ref<any[]>([])

// 表单引用
const formRef = ref()

// 验证码倒计时
const countdown = ref(0)
const isCountingDown = ref(false)

// 数据字典和省市列表
const nationalityList = ref([]) // 民族列表
const provinceList = ref([]) // 省市列表
const showNationalityPicker = ref(false) // 显示民族选择器
const showNativePlacePicker = ref(false) // 显示籍贯选择器

// 表单验证规则
const formRules = {
	realName: [
		{ required: true, message: '请输入真实姓名', trigger: 'blur' },
		{ min: 2, message: '姓名至少2个字符', trigger: 'blur' },
		{ max: 20, message: '姓名不能超过20个字符', trigger: 'blur' }
	],
	idNumber: [
		{ required: true, message: '请输入身份证号', trigger: 'blur' },
		{ len: 18, message: '身份证号必须为18位', trigger: 'blur' },
		{ pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号格式', trigger: 'blur' },
		{ 
			validator: (rule: any, value: string, callback: any) => {
				if (!value) {
					callback(new Error('请输入身份证号'))
					return
				}
				if (value.length !== 18) {
					callback(new Error('身份证号必须为18位'))
					return
				}
				if (!/^\d{17}[\dXx]$/.test(value)) {
					callback(new Error('身份证号格式不正确'))
					return
				}
				// 验证身份证号校验码
				const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
				const codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
				let sum = 0
				for (let i = 0; i < 17; i++) {
					sum += parseInt(value[i]) * weights[i]
				}
				const checkCode = codes[sum % 11]
				if (value[17].toUpperCase() !== checkCode) {
					callback(new Error('身份证号校验码错误'))
					return
				}
				callback()
			}, 
			trigger: 'blur' 
		}
	],
	phone: [
		{ required: true, message: '请输入手机号', trigger: 'blur' },
		{ len: 11, message: '手机号必须为11位', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
		{ 
			validator: (rule: any, value: string, callback: any) => {
				if (!value) {
					callback(new Error('请输入手机号'))
					return
				}
				if (value.length !== 11) {
					callback(new Error('手机号必须为11位'))
					return
				}
				if (!/^1[3-9]\d{9}$/.test(value)) {
					callback(new Error('请输入正确的手机号'))
					return
				}
				// 验证手机号段
				const validPrefixes = [
					'130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
					'150', '151', '152', '153', '155', '156', '157', '158', '159',
					'166', '167',
					'170', '171', '172', '173', '175', '176', '177',
					'180', '181', '182', '183', '184', '185', '186', '187', '188', '189',
					'190', '191', '192', '193', '195', '196', '197', '198', '199'
				]
				const prefix = value.substring(0, 3)
				if (!validPrefixes.includes(prefix)) {
					callback(new Error('手机号段不正确'))
					return
				}
				callback()
			}, 
			trigger: 'blur' 
		}
	],
	verificationCode: [
		{ required: true, message: '请输入验证码', trigger: 'blur' },
		{ len: 6, message: '验证码为6位数字', trigger: 'blur' },
		{ pattern: /^\d{6}$/, message: '验证码必须为6位数字', trigger: 'blur' }
	]
}

// 样式配置
const navbarStyle = {
	backgroundColor: '#FFFFFF',
	borderBottom: '1rpx solid #F0F0F0',
	height: '88rpx',
	position: 'fixed',
	top: '0',
	left: '0',
	right: '0',
	zIndex: '999'
}

const inputStyle = {
	backgroundColor: '#F8F8F8',
	borderRadius: '8rpx',
	padding: '20rpx',
	fontSize: '28rpx',
	color: '#333333'
}

// 验证码按钮样式（计算属性）
const codeBtnStyle = computed(() => {
	const hasPhone = formData.value.phone.trim().length > 0
	const isValidPhone = /^1[3-9]\d{9}$/.test(formData.value.phone.trim())
	const isDisabled = !hasPhone || !isValidPhone || isCountingDown.value
	
	return {
		backgroundColor: isDisabled ? '#F0F0F0' : 'var(--u-primary)',
		borderColor: isDisabled ? '#F0F0F0' : 'var(--u-primary)',
		color: isDisabled ? '#999999' : '#FFFFFF',
		fontSize: '24rpx',
		padding: '12rpx 16rpx',
		borderRadius: '6rpx',
		marginLeft: '10rpx',
		opacity: isDisabled ? '0.6' : '1'
	}
})

// 选择器按钮样式
const pickerButtonStyle = {
	backgroundColor: '#F8F8F8',
	color: '#333333',
	border: '1rpx solid #E0E0E0',
	fontSize: '28rpx',
	height: '80rpx',
	lineHeight: '80rpx',
	padding: '0 20rpx',
	borderRadius: '8rpx',
	textAlign: 'left',
	justifyContent: 'flex-start'
}

// 表单是否有效的计算属性
const isFormValid = computed(() => {
	const hasRealName = formData.value.realName.trim().length >= 2
	const hasIdNumber = formData.value.idNumber.trim().length === 18
	const hasPhone = formData.value.phone.trim().length === 11
	const hasVerificationCode = formData.value.verificationCode.trim().length === 6
	const hasIdCardFront = idCardFront.value.length > 0
	const hasIdCardBack = idCardBack.value.length > 0
	const hasAgreed = agreed.value.length > 0
	
	return hasRealName && hasIdNumber && hasPhone && hasVerificationCode && hasIdCardFront && hasIdCardBack && hasAgreed
})

const checkboxStyle = {
	marginRight: '10rpx'
}

const submitBtnStyle = {
	width: '100%',
	height: '88rpx',
	fontSize: '32rpx',
	fontWeight: 'bold',
	borderRadius: '12rpx',
	backgroundColor: 'var(--u-primary)',
	borderColor: 'var(--u-primary)'
}

// 检查openId是否有效
function checkOpenId() {
	if (!openId.value) {
		uni.showToast({
			title: '用户身份验证失败，请重新进入应用',
			icon: 'none'
		})
		return false
	}
	return true
}

// 返回上一页
function goBack() {
	uni.navigateBack()
}

// 处理OCR成功事件
function handleOcrSuccess(event: { type: 'front' | 'back', data: any }) {
	if (event.type === 'front') {
		ocrData.value.front = event.data
		// 自动填充正面信息
		if (event.data.name && !formData.value.realName) {
			formData.value.realName = event.data.name
		}
		if (event.data.idCardNo && !formData.value.idNumber) {
			formData.value.idNumber = event.data.idCardNo
		}
		if (event.data.address && !formData.value.address) {
			formData.value.address = event.data.address
		}
		if (event.data.age && !formData.value.age) {
			formData.value.age = event.data.age.toString()
		}
		if (event.data.birthday && !formData.value.birthday) {
			// 将YYYYMMDD格式转换为YYYY-MM-DD格式
			const birthday = event.data.birthday
			if (birthday.length === 8) {
				formData.value.birthday = `${birthday.substring(0, 4)}-${birthday.substring(4, 6)}-${birthday.substring(6, 8)}`
			}
		}
		if (event.data.gender && !formData.value.gender) {
			// 性别：1-男，2-女
			formData.value.gender = event.data.gender === 1 ? '男' : '女'
			formData.value.genderID = event.data.gender.toString()
		}
		if (event.data.nationalityID && !formData.value.nationalityID) {
			// 民族ID
			formData.value.nationalityID = event.data.nationalityID
			// 需要根据ID查找对应的民族名称
			const nationalityItem = nationalityList.value.find(item => item.id === event.data.nationalityID)
			if (nationalityItem) {
				formData.value.nationalityName = nationalityItem.fullName
			}
		}
		if (event.data.nativePlace && !formData.value.nativePlaceID) {
			// 籍贯ID数组
			formData.value.nativePlaceID = event.data.nativePlace
			// 解析籍贯ID数组，获取省份名称
			try {
				const placeIds = JSON.parse(event.data.nativePlace)
				if (Array.isArray(placeIds) && placeIds.length > 0) {
					const provinceId = placeIds[0] // 取第一个ID作为省份
					const provinceItem = provinceList.value.find(item => item.id === provinceId)
					if (provinceItem) {
						formData.value.nativePlace = provinceItem.fullName
					}
				}
			} catch (error) {
				console.error('解析籍贯ID失败:', error)
			}
		}
	} else if (event.type === 'back') {
		ocrData.value.back = event.data
		// 自动填充反面信息
		if (event.data.idCardValidStart && !formData.value.idCardValidStart) {
			// 将YYYYMMDD格式转换为YYYY-MM-DD格式
			const startDate = event.data.idCardValidStart
			if (startDate.length === 8) {
				formData.value.idCardValidStart = `${startDate.substring(0, 4)}-${startDate.substring(4, 6)}-${startDate.substring(6, 8)}`
			}
		}
		if (event.data.idCardValidEnd && !formData.value.idCardValidEnd) {
			// 将YYYYMMDD格式转换为YYYY-MM-DD格式
			const endDate = event.data.idCardValidEnd
			if (endDate.length === 8) {
				formData.value.idCardValidEnd = `${endDate.substring(0, 4)}-${endDate.substring(4, 6)}-${endDate.substring(6, 8)}`
			}
		}
	}
}

// 处理OCR错误事件
function handleOcrError(event: { type: 'front' | 'back', message: string }) {
	console.error(`OCR验证失败 (${event.type}):`, event.message)
}





// 获取民族列表
const getNationalityList = async () => {
	try {
		const result = await systemApi.getListByTypeDataCode('Nation')
		if (result && result.code === 200) {
			nationalityList.value = result.data || []
		}
	} catch (error) {
		console.error('获取民族列表失败:', error)
	}
}

// 获取省市列表
const getProvinceList = async () => {
	try {
		const result = await systemApi.getAllProByMapList(1) // 只查询省
		if (result && result.code === 200) {
			provinceList.value = result.data || []
			console.log(provinceList.value)
		}
	} catch (error) {
		console.error('获取省市列表失败:', error)
	}
}

// 显示民族选择器
const showNationalitySelector = () => {
	showNationalityPicker.value = true
}

// 显示籍贯选择器
const showNativePlaceSelector = () => {
	showNativePlacePicker.value = true
}

// 获取民族选择器的默认索引
const getNationalityDefaultIndex = () => {
	if (!formData.value.nationalityName || nationalityList.value.length === 0) {
		return 0
	}
	const index = nationalityList.value.findIndex(item => item.fullName === formData.value.nationalityName)
	return index >= 0 ? index : 0
}

// 获取籍贯选择器的默认索引
const getNativePlaceDefaultIndex = () => {
	if (!formData.value.nativePlace || provinceList.value.length === 0) {
		return 0
	}
	const index = provinceList.value.findIndex(item => (item.fullName || item.name) === formData.value.nativePlace)
	return index >= 0 ? index : 0
}

// 性别变化处理
const onGenderChange = (value: string) => {
	formData.value.gender = value
	formData.value.genderID = value === '男' ? '1' : '2'
}

// 选择民族
const onNationalitySelect = (e: any) => {
	const selectedName = e.value[0]
	const selectedItem = nationalityList.value.find(item => item.fullName === selectedName)
	if (selectedItem) {
		formData.value.nationalityID = selectedItem.id
		formData.value.nationalityName = selectedItem.fullName
	}
	showNationalityPicker.value = false
}

// 选择籍贯
const onNativePlaceSelect = (e: any) => {
	const selectedName = e.value[0]
	const selectedItem = provinceList.value.find(item => (item.fullName || item.name) === selectedName)
	if (selectedItem) {
		formData.value.nativePlace = selectedItem.fullName || selectedItem.name
		formData.value.nativePlaceID = selectedItem.id
	}
	showNativePlacePicker.value = false
}

// 显示生日选择器
const showBirthdayPicker = () => {
	uni.showActionSheet({
		itemList: ['选择日期'],
		success: () => {
			// 使用uview的日期选择器
			showBirthdayDatePicker.value = true
		}
	})
}

// 生日日期选择器状态
const showBirthdayDatePicker = ref(false)

// 生日日期选择
const onBirthdaySelect = (e: any) => {
	formData.value.birthday = e.value
	showBirthdayDatePicker.value = false
}

// 身份证有效期开始日期选择器状态
const showIdCardStartPicker = ref(false)

// 显示身份证有效期开始日期选择器
const showIdCardStartDatePicker = () => {
	showIdCardStartPicker.value = true
}

// 身份证有效期开始日期选择
const onIdCardStartSelect = (e: any) => {
	formData.value.idCardValidStart = e.value
	showIdCardStartPicker.value = false
}

// 身份证有效期结束日期选择器状态
const showIdCardEndPicker = ref(false)

// 显示身份证有效期结束日期选择器
const showIdCardEndDatePicker = () => {
	showIdCardEndPicker.value = true
}

// 身份证有效期结束日期选择
const onIdCardEndSelect = (e: any) => {
	formData.value.idCardValidEnd = e.value
	showIdCardEndPicker.value = false
}

// 获取验证码
async function getVerificationCode() {
	if (!formData.value.phone.trim()) {
		uni.showToast({
			title: '请先输入手机号',
			icon: 'none'
		})
		return
	}
	
	// 验证手机号格式
	if (!/^1[3-9]\d{9}$/.test(formData.value.phone.trim())) {
		uni.showToast({
			title: '请输入正确的手机号格式',
			icon: 'none'
		})
		return
	}
	
	// 开始倒计时
	isCountingDown.value = true
	countdown.value = 60
	
	const timer = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
			clearInterval(timer)
			isCountingDown.value = false
		}
	}, 1000)
	
	try {
    // 调用发送验证码接口（实名）：/appToHr/ocrIdCard/{type}
    const result = await verifyApi.sendVerifyCode(formData.value.phone.trim(), 'realName')
		
		if (result && result.code === 200) {
			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			})
		} else {
			// 接口返回错误，停止倒计时
			clearInterval(timer)
			isCountingDown.value = false
			countdown.value = 0
			
			uni.showToast({
				title: result?.message || '验证码发送失败',
				icon: 'none'
			})
		}
	} catch (error) {
		// 网络错误，停止倒计时
		clearInterval(timer)
		isCountingDown.value = false
		countdown.value = 0
		
		console.error('发送验证码失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	}
}

// 查看协议
function viewAgreement() {
	uni.showToast({
		title: '查看协议',
		icon: 'none'
	})
}

// 页面加载时检查openId
onMounted(() => {
	// 更新openId引用
	openId.value = userStore.getOpenId() || ''
	
	checkOpenId()
	
	// 初始化数据字典和省市列表
	getNationalityList()
	getProvinceList()
})

// 表单验证函数（保留用于自定义验证逻辑）
function validateRealName() {
	// 使用uview-plus的表单验证
}

function validateIdNumber() {
	// 使用uview-plus的表单验证
}

function validatePhone() {
	// 使用uview-plus的表单验证
}

function validateVerificationCode() {
	// 使用uview-plus的表单验证
}

// 提交认证
async function submitVerification() {
	console.log('提交认证按钮被点击')
	
	// 验证身份证图片
	if (!idCardFront.value) {
		uni.showToast({
			title: '请上传身份证人像面',
			icon: 'none'
		})
		return
	}
	
	if (!idCardBack.value) {
		uni.showToast({
			title: '请上传身份证国徽面',
			icon: 'none'
		})
		return
	}
	
	// 验证表单数据
	if (!formData.value.realName.trim()) {
		uni.showToast({
			title: '请输入真实姓名',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.idNumber.trim()) {
		uni.showToast({
			title: '请输入身份证号',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.phone.trim()) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.verificationCode.trim()) {
		uni.showToast({
			title: '请输入验证码',
			icon: 'none'
		})
		return
	}
	
	// 验证新添加的字段
	if (!formData.value.birthday.trim()) {
		uni.showToast({
			title: '请选择生日',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.gender) {
		uni.showToast({
			title: '请选择性别',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.age.trim()) {
		uni.showToast({
			title: '请输入年龄',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.nationalityID.trim()) {
		uni.showToast({
			title: '请选择民族',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.address.trim()) {
		uni.showToast({
			title: '请输入住址',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.nativePlace.trim()) {
		uni.showToast({
			title: '请选择籍贯',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.idCardValidStart.trim()) {
		uni.showToast({
			title: '请选择身份证有效期开始日期',
			icon: 'none'
		})
		return
	}
	
	if (!formData.value.idCardValidEnd.trim()) {
		uni.showToast({
			title: '请选择身份证有效期结束日期',
			icon: 'none'
		})
		return
	}
	
	if (agreed.value.length === 0) {
		uni.showToast({
			title: '请先同意服务协议',
			icon: 'none'
		})
		return
	}
	
	// 验证OCR是否已完成
	if (!ocrData.value.front || !ocrData.value.back) {
		uni.showToast({
			title: '请先完成身份证验证',
			icon: 'none'
		})
		return
	}
	
	// 验证openId是否已获取
	if (!checkOpenId()) {
		return
	}
	
	// 显示加载提示
	uni.showLoading({
		title: '提交认证信息...'
	})
	
    try {
        // 按接口约定：无需单独验证验证码，直接随创建用户接口一并提交
		
        // 合并OCR返回的信息和用户输入的信息（OCR 全量 + 表单 + 验证码）
		const mergedOcrData = {
			idCardFront: ocrData.value.front?.idCardFront,
			idCardBack: ocrData.value.back?.idCardBack
		}
		console.log('发', ocrData.value,mergedOcrData.idCardBack)
		
		// 先构建基础用户数据
        const userData = {
			openId: openId.value,
			name: formData.value.realName.trim(),
			idCardNo: formData.value.idNumber.trim(),
			phone: formData.value.phone.trim(),
            code: formData.value.verificationCode.trim(),
			birthday: formData.value.birthday.trim(),
			gender: formData.value.genderID, // 使用性别ID
			age: formData.value.age,
			nationalityID: formData.value.nationalityID,
			address: formData.value.address.trim(),
			nativePlace: formData.value.nativePlaceID, // 使用籍贯ID
			idCardValidStart: formData.value.idCardValidStart.trim(),
			idCardValidEnd: formData.value.idCardValidEnd.trim()
		}
		
        // 然后添加OCR数据，但不覆盖已有的字段（保留全部 OCR 字段）
        const finalUserData = {
            ...mergedOcrData,
            ...userData  // 确保表单数据优先级最高
        }
		
		// 调试信息
		console.log('openId:', openId.value)
		console.log('表单数据:', formData.value)
		console.log('身份证正面:', idCardFront.value)
		console.log('身份证反面:', idCardBack.value)
		console.log('OCR数据:', ocrData.value)
		console.log('提交的用户数据:', finalUserData)
		
		// 检查表单数据是否为空
		if (!formData.value.realName || !formData.value.idNumber || !formData.value.phone) {
			console.error('表单数据为空，请检查输入框绑定')
			uni.hideLoading()
			uni.showToast({
				title: '表单数据不完整，请重新填写',
				icon: 'none'
			})
			return
		}
		
		const result = await userApi.createAppUser(finalUserData)
		
		// 隐藏加载提示
		uni.hideLoading()
		
		if (result && result.code === 200) {
			console.log('实名认证接口调用成功:', result)
			
			// 更新用户缓存中的实名认证信息
			const success = userStore.updateVerificationInfo(
				formData.value.realName,
				formData.value.idNumber,
			)
			
            if (success) {
                // 明文寫入手機號到快取（僅我的頁展示時再脫敏）
                userStore.updateUserInfo({
                    phone: formData.value.phone.trim()
                })
				// 显示提交成功
				uni.showToast({
					title: '认证提交成功',
					icon: 'success'
				})
				
                setTimeout(() => {
                    // 跳转到实名认证成功页面（該頁非 tabBar，使用 navigateTo）
                    uni.navigateTo({
                        url: '/pages/verification-success/verification-success'
                    })
                }, 1500)
			} else {
				uni.showToast({
					title: '认证失败，请重试',
					icon: 'none'
				})
			}
		} else {
			// 接口返回错误
			console.error('实名认证接口返回错误:', result)
			uni.showToast({
				title: result?.msg || result?.message || '认证失败，请重试',
				icon: 'none'
			})
		}
	} catch (error) {
		// 隐藏加载提示
		uni.hideLoading()
		
		console.error('创建实名信息失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	}
}
</script>

<style lang="scss" scoped>
.verification-page {
	min-height: 100vh;
	background-color: #F5F5F5;
	padding-bottom: 10rpx;
	
}

/* 头部样式已使用u-navbar组件 */

.intro-text {
	padding: 20rpx;
	margin-bottom: 0rpx;
}



.form-section {
	padding: 30rpx;
	background-color: #FFFFFF;
	margin-bottom: calc(200rpx + env(safe-area-inset-bottom));
}

.bottom-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	border-top: 1rpx solid #F0F0F0;
	padding: 20rpx 30rpx calc(40rpx + env(safe-area-inset-bottom)) 30rpx;
	z-index: 100;
	background-color: #FFFFFF;
}

.agreement-section {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
	
	.agreement-text {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.4;
		
		.agreement-link {
			color: var(--u-primary);
		}
	}
}

.submit-section {
	// u-button 组件会自动处理样式
}

/* 选择器输入框样式 - 与其他输入框保持一致 */
.select-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  height: 80rpx;
  box-sizing: border-box;
}

.select-text {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.select-text.placeholder {
  color: #999999;
}

.arrow-icon {
  font-size: 24rpx;
  color: #999999;
  margin-left: 10rpx;
}
</style> 